package com.breachwalls.mogen.plugin.generator;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;

import com.breachwalls.mogen.generator.LocalModelGenerationProperties;

public class EclipseModelGeneratorProperties extends LocalModelGenerationProperties {

    private File defaultTemplateLocation;

    public EclipseModelGeneratorProperties(final EclipseModelGeneratorConfigurer configure) {
        Properties properties = new Properties();
        InputStream is = null;

        try {
            is = new FileInputStream(configure.getConfigLocation());
            properties.load(is);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }

        setBaseDirectory(configure.getProjectLocation());
        setProperties(properties);
        this.defaultTemplateLocation = configure.getPluginLocation();
    }

    @Override
    public File getOutputDirectory() {
        String dirname = getProperties().getProperty(OUTPUT_DIRECTORY_KEY);
        return new File(getBaseDirectory(), dirname);
    }

    @Override
    public File getTemplateLocation() {
        String dirname = getProperties().getProperty(TEMPLATE_LOCATION_KEY);
        if (StringUtils.isEmpty(dirname)) {
            // テンプレのロケーションが指定されていなければ、プラグインのデフォルトを使用する
            return new File(defaultTemplateLocation, "mogen-templates");
        } else {
            // テンプレのロケーションが指定されていたら、その情報を用いる
            return super.getTemplateLocation();
        }
    }

    @Override
    public File[] getConfigDirectories() {
        String dirname = getProperties().getProperty(CONFIG_DIRECTORY_KEY);
        File dir = new File(getBaseDirectory(), dirname);
        if (!dir.isDirectory()) {
            throw new IllegalArgumentException("[" + dir.getAbsolutePath() + "] is not directory.");
        }
        return new File[] {dir, getDefaultConfigFile()};
    }

    @Override
    protected File getDefaultConfigFile() {
        return this.defaultTemplateLocation;
    }

}
